<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                               |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: xiangminghu@clcw.com.cn                                        |
// +------------------------------------------------------------------------+
//
namespace AuctionBack\Controller;

use AuctionCore\Common\AjaxPage;
use AuctionCore\Common\Image;
use AuctionCore\Common\PhpRedis;
use AuctionCore\Common\Util;
use AuctionCore\System\SystemLog;

/**
 * Class ArticleCrawlerController
 *
 * 文章采集数据
 *
 * @package AuctionBack\Controller
 */
class ArticleCrawlerController extends BaseController
{
    protected $articleLogic;

    protected $articleCrawlerLogic;

    protected $articleCategoryLogic;

    private $empId;

    public function __construct()
    {
        parent::__construct();

        $this->articleLogic = D('Article', 'Logic');

        $this->articleCrawlerLogic = D('ArticleCrawler', 'Logic');

        $this->articleCategoryLogic = D('ArticleCategory', 'Logic');

        $this->empId = $this->user_info['emp_id'];
    }

    public function index()
    {
        $category = $this->articleCategoryLogic->getParentArticleCategory();
        $this->assign('cate', $category);
        $this->display();
    }

    public function getChildCategory()
    {
        $parentId = I('get.category_id/d', 0);
        $category = $this->articleCategoryLogic->getArticleCategoryByPid($parentId);
        echo json_encode($category);
    }

    /**
     * 资讯列表
     */
    public function articleCrawlerList()
    {
        $params = [];
        $page = I('get.p', 1);
        $pageSize = 10;
        $params['category_id'] = I('get.category_id/d', 0);
        $params['child_id'] = I('get.child_id/d', 0);
        $params['article_title'] = I('get.article_title', '', 'trim');
        $params['article_type'] = I('get.article_type');
        $params['article_from'] = I('get.article_from');
        $params['start_time'] = I('get.start_time');
        $params['end_time'] = I('get.end_time');
        if (isset($_GET['status'])) {
            $params['status'] = I('get.status');
        }
        if (isset($_GET['is_top'])) {
            $params['is_top'] = I('get.is_top');
        }
        $data = $this->articleCrawlerLogic->getArticleCrawlerList($page, $pageSize, $params);
        $category = $this->articleCategoryLogic->getArticleCategory();
        $cate = [];
        foreach ($category as $v) {
            $cate[$v['category_id']] = $v;
        }
        $Page = new AjaxPage($data['total'], $pageSize, "get_page");
        $Page->setConfig('theme', " %totalRow% %header% %nowPage%/%totalPage% 页 %first% %upPage% %prePage% %linkPage% %nextPage% %downPage%  %end% %jumpform%");
        $show = $Page->show();// 分页显示输出
        $this->assign('date', date('Y-m-d'));
        $this->assign('page', $show);
        $this->assign('article', $data['list']);
        $this->assign('cate', $cate);
        $this->display();
    }

    /**
     * 添加文章
     */
    public function editArticleCrawler()
    {
        $id = I('get.id/d', 0);

        $article = $this->articleCrawlerLogic->getArticleCrawlerById($id);
        $child = $this->articleCategoryLogic->getArticleCategoryByPid($article['category_id']);

        $category = $this->articleCategoryLogic->getArticleCategoryByPid(0);

        $this->assign('child', $child);
        $this->assign('article', $article);
        $this->assign('category', $category);

        $this->display();
    }

    /**
     * 保存文章
     */
    public function saveArticleCrawler()
    {
        $data = [
            'id'              => I('post.id/d', 0),
            'article_title'   => I('post.title', ''),
            'author'          => I('post.author', ''),
            'category_id'     => I('post.category/d', 0),
            'child_id'        => I('post.child/d', 0),
            'is_top'          => I('post.top', 0),
            'article_focus'   => I('post.focus', ''),
            'article_thumb'   => I('post.thumb', ''),
            'article_desc'    => I('post.desc', ''),
            'article_content' => I('post.content', ''),
            'update_time'     => time(),
            'cron_time'       => I('post.publish_time'),
        ];

        if (!empty($data['cron_time'])) {
            $data['cron_time'] = strtotime($data['cron_time']);
            $data['status'] = 3;
            if ($this->articleLogic->isLockCronPublish()){
                echo Util::auto_jsonp_or_json($_REQUEST, ['code' => '300', 'msg' => '定时发布锁定中,请重试']);
                return;
            }

            $this->articleLogic->LockCronPublish();
        }

        $res = $this->articleCrawlerLogic->saveArticleCrawler($data);
        if ($res) {
            if (!empty($data['id'])) {
                $id = $data['id'];
            } else {
                $id = $res;
            }
            if ($data['status'] == 3) {
                D('Article', 'Logic')->cronPublish($id, $data['cron_time'], '200000');
                $this->articleLogic->unlockCronPublish();
            }
            SystemLog::add(
                [
                    'emp_id' => $this->empId,
                    'action' => '保存资讯'
                ]
            );
            echo Util::auto_jsonp_or_json(
                $_REQUEST,
                [
                    'code' => '200',
                    'msg'  => '资讯保存成功',
                    'data' => $res
                ]
            );
            die;
        } else {
            echo Util::auto_jsonp_or_json(
                $_REQUEST,
                [
                    'code' => '5',
                    'msg'  => '资讯保存失败,请重试',
                    'data' => $res
                ]
            );
            die;
        }
    }

    /**
     * 文章预览
     */
    public function show()
    {
        $articleID = I('get.id/d', 0);

        $article = $this->articleCrawlerLogic->getArticleCrawlerByID($articleID);
        $article['create_time'] = date('Y-m-d H:i:s', $article['create_time']);
        if ($article['type'] == 1) {
            $category = $this->articleCategoryLogic->getArticleCategoryById($article['category_id']);
            $child = $this->articleCategoryLogic->getArticleCategoryById($article['child_id']);
            $categoryName = $category['category_title'] . '-' . $child['category_title'];
        } else {
            $categoryName = $article['from_name'];
        }
        $this->assign('categoryName', $categoryName);
        $this->assign('article', $article);
        $this->display();
    }

    /**
     * 文章发布
     */
    public function articleCrawlerPublish()
    {
        $id = I('post.id');
        $status = I('post.status');
        if ($id && $status) {
            $time = time();
            $data = [
                'id'           => $id,
                'status'       => $status,
                'update_time'  => $time,
                'publish_time' => $time
            ];

            $res = $this->articleCrawlerLogic->saveArticleCrawler($data);

            if ($res) {
                $redis = new PhpRedis(0);
                $keyName = getRedisKeyByCode('REDIS_KEY','100001');
                $redis->lpush(
                    $keyName,
                    json_encode(
                        [
                            'bizContent' => [
                                "articleId" => (int)$id
                            ],
                            'bizType'    => 1
                        ]
                    )
                );
                SystemLog::add(['emp_id' => $this->empId, 'action' => '发布成功']);
                echo Util::auto_jsonp_or_json($_REQUEST, ['code' => '200', 'msg' => '']);
                die;
            }
        }
        echo Util::auto_jsonp_or_json($_REQUEST, ['code' => '5', 'msg' => '']);
        die;
    }

    public function ueditor()
    {
        $action = I('get.action');
        if ($action == 'config') {
            $config = [
                "imageActionName" => "upload", /* 执行上传图片的action名称 */
                "imageFieldName"  => "upfile", /* 提交的图片表单名称 */
                "imageMaxSize"    => 2048000, /* 上传大小限制，单位B */
                "imageAllowFiles" => [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上传图片格式显示 */
                'imageUrlPrefix'  => '',
            ];
            $result = json_encode($config);
        } elseif ($action == 'upload') {
            $ret = [];
            foreach ($_FILES as $key => $file) {
                $tmpFile = $file['tmp_name'];
                $object = $tmpFile . '.' . get_extension($file['name']);
                $ret[] = Image::upload_file_by_file(OSS_BUCKET, $object, $tmpFile, null, '', 'article');
            }
            $data = [
                "state"    => "SUCCESS",          //上传状态，上传成功时必须返回"SUCCESS"
                "url"      => get_content_cdnurl() . current($ret),            //返回的地址
                "title"    => "",          //新文件名
                "original" => "",       //原始文件名
                "type"     => "",            //文件类型
                "size"     => "",           //文件大小
            ];
            $result = json_encode($data);
        }
        echo $result;
    }

    public function uploadPic()
    {
        try {
            $ret = [];
            foreach ($_FILES as $key => $file) {
                $tmpFile = $file['tmp_name'];
                $object = $tmpFile . '.' . get_extension($file['name']);
                $ret[] = Image::upload_file_by_file(OSS_BUCKET, $object, $tmpFile, null, '', 'carousel');
            }
            echo Util::auto_jsonp_or_json($_REQUEST, ['code' => '200', 'msg' => '', 'data' => $ret]);
            exit;
        } catch (\Exception $e) {
            echo Util::auto_jsonp_or_json($_REQUEST, ['code' => '5', 'msg' => $e->getMessage()]);
            exit;
        }
    }
}